'use client';

import type { IPost, IPostReviewHistory } from '@/interfaces';
import { useQuery } from '@tanstack/react-query';
import { queryAllPostReviewHistoryById } from '@/services/api';
import useModal from '@/hooks/useModal';
import classNames from 'classnames';
import { toRelativeTime } from '@/lib/tool';
import type { TPostCompositeState } from '@/types';
import Alert from '@/app/[locale]/alert/alert';
import { useTranslations } from 'use-intl';
import {
  postCompositeStateTranslator,
  postSortStateTranslator,
} from '@/lib/translator';

export default function PostReviewHistory(
  this: any,
  { item }: { item: IPost },
) {
  const { showModal } = useModal();
  const t = useTranslations('PostIdPage');

  const queryAllPostReviewHistoryByIdQuery = useQuery(
    ['/forum', '/posts', item.id, '/reviewHistory'],
    async (context) => {
      return (await queryAllPostReviewHistoryById({
        id: context.queryKey[2] + '',
      })) as IPostReviewHistory[];
    },
  );

  function onClickHistory(data: IPostReviewHistory[]) {
    showModal({
      title: t('auditRecords'),
      centered: false,
      content: <ReviewHistory data={data} createdOn={item.createdOn} />,
      isShowFooter: false,
      large: true,
    });
  }

  if (queryAllPostReviewHistoryByIdQuery.data) {
    const data = queryAllPostReviewHistoryByIdQuery.data;
    return (
      <i
        className="bi bi-clock-history cursor-pointer"
        onClick={onClickHistory.bind(this, data)}
      ></i>
    );
  }

  return (
    <span
      className="spinner-grow spinner-grow-sm"
      role="status"
      aria-hidden="true"
    ></span>
  );
}

const ReviewHistory = ({
  data,
  createdOn,
}: {
  data: IPostReviewHistory[];
  createdOn: string;
}) => {
  const reviewStates: IPostReviewHistory[] = [];
  const sortStates: IPostReviewHistory[] = [];
  let _isDefault = false;

  data.forEach((item) => {
    if (item.previousReviewState && item.finalReviewState) {
      reviewStates.push(item);
    } else if (item.previousSortState && item.finalSortState) {
      sortStates.push(item);
    }
  });

  if (data.length === 0) {
    _isDefault = true;
    const defaultItem: any = {
      id: 1,
      previousReviewState: 'PENDING',
      finalReviewState: 'APPROVED',
      createdOn,
      _isDefault,
    };
    reviewStates.push(defaultItem);
  }

  return (
    <div className="vstack gap-3">
      {reviewStates.length > 0 && (
        <CompositeStateTable items={reviewStates} _isDefault={_isDefault} />
      )}
      {sortStates.length > 0 && <SortStateTable items={sortStates} />}
      {reviewStates.length === 0 && sortStates.length === 0 && (
        <Alert message="nodata" />
      )}
    </div>
  );
};

const CompositeStateTable = ({
  items,
  _isDefault,
}: {
  items: IPostReviewHistory[];
  _isDefault?: boolean;
}) => {
  const t = useTranslations('PostIdPage');

  return (
    <div className="table-responsive">
      <table className="table table-hover align-middle">
        <thead>
          <tr className="text-nowrap">
            <th scope="col" className="fw-normal text-nowrap">
              {t('auditStatus')}
            </th>

            {!_isDefault && (
              <th scope="col" className="fw-normal text-nowrap">
                {t('auditReason')}
              </th>
            )}

            <th scope="col" className="fw-normal text-nowrap">
              {t('auditPersonnel')}
            </th>
            <th scope="col" className="fw-normal text-nowrap">
              {t('auditTime')}
            </th>
          </tr>
        </thead>
        <tbody>
          {items.map((item, index) => {
            return (
              <tr key={item.id} className="text-nowrap">
                <td>
                  {item.previousReviewState && item.finalReviewState && (
                    <div className="row flex-nowrap">
                      <div className="col-auto">
                        <CompositeStateIcon
                          compositeState={item.finalReviewState}
                        />
                      </div>
                      <div className="col-auto">
                        {t(postCompositeStateTranslator(item.finalReviewState))}
                      </div>
                      <div className="col-auto">
                        <i
                          className={classNames(
                            'bi bi-arrow-left',
                            index === 0 ? 'text-primary' : 'text-secondary',
                          )}
                        ></i>
                      </div>
                      <div className="col-auto text-secondary">
                        {t(
                          postCompositeStateTranslator(
                            item.previousReviewState,
                          ),
                        )}
                      </div>
                    </div>
                  )}
                </td>

                {!item._isDefault && (
                  <td title={item.reason || ''} className="text-wrap">
                    <div
                      dangerouslySetInnerHTML={{
                        __html: item.reason || '',
                      }}
                    ></div>
                  </td>
                )}

                <td>
                  {item._isDefault
                    ? t('system')
                    : `${item.reviewer.alias} (${item.reviewer.id})`}
                </td>
                <td>
                  <time dateTime={item.createdOn} title={item.createdOn}>
                    {toRelativeTime(item.createdOn)}
                  </time>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

const SortStateTable = ({ items }: { items: IPostReviewHistory[] }) => {
  const t = useTranslations('PostIdPage');

  return (
    <div className="table-responsive">
      <table className="table table-hover align-middle">
        <thead>
          <tr className="text-nowrap">
            <th scope="col" className="fw-normal text-nowrap">
              {t('sortingStatus')}
            </th>
            <th scope="col" className="fw-normal text-nowrap">
              {t('sortingReason')}
            </th>
            <th scope="col" className="fw-normal text-nowrap">
              {t('auditPersonnel')}
            </th>
            <th scope="col" className="fw-normal text-nowrap">
              {t('auditTime')}
            </th>
          </tr>
        </thead>
        <tbody>
          {items.map((item, index) => {
            return (
              <tr key={item.id} className="text-nowrap">
                <td>
                  {item.previousSortState && item.finalSortState && (
                    <div className="row flex-nowrap">
                      <div className="col-auto">
                        {t(postSortStateTranslator(item.finalSortState))}
                      </div>
                      <div className="col-auto">
                        <i
                          className={classNames(
                            'bi bi-arrow-left',
                            index === 0 ? 'text-primary' : 'text-secondary',
                          )}
                        ></i>
                      </div>
                      <div className="col-auto text-secondary">
                        {t(postSortStateTranslator(item.previousSortState))}
                      </div>
                    </div>
                  )}
                </td>
                <td title={item.sortReason || ''} className="text-wrap">
                  <div
                    dangerouslySetInnerHTML={{
                      __html: item.sortReason || '',
                    }}
                  ></div>
                </td>
                <td>{`${item.reviewer.alias} (${item.reviewer.id})`}</td>
                <td>
                  <time dateTime={item.createdOn} title={item.createdOn}>
                    {toRelativeTime(item.createdOn)}
                  </time>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

const CompositeStateIcon = ({
  compositeState,
}: {
  compositeState: TPostCompositeState;
}) => {
  return (
    <>
      {compositeState === 'APPROVED' && (
        <i className="bi bi-patch-check-fill text-success"></i>
      )}

      {compositeState === 'PENDING' && (
        <i className="bi bi-patch-check-fill text-secondary"></i>
      )}

      {compositeState === 'DENIED' && (
        <i className="bi bi-patch-check-fill text-danger"></i>
      )}

      {compositeState === 'CLOSE' && (
        <i className="bi bi-patch-check-fill text-black"></i>
      )}

      {compositeState === 'SHOW' && (
        <i className="bi bi-patch-check text-success"></i>
      )}

      {compositeState === 'HIDE' && (
        <i className="bi bi-patch-check text-danger"></i>
      )}

      {compositeState === 'LOCK' && (
        <i className="bi bi-patch-check text-secondary"></i>
      )}
    </>
  );
};
